package com.application.magazine;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.ImageLoadingListener;
import com.roscopeco.ormdroid.Entity;

public class BookInformation extends Activity {
	private ImageView goback;
	private DisplayImageOptions options;
	private Item_Magazine objBean;
	ImageLoader imageLoader;
	ProgressBar progress;
	String pdfUrl;
	TextView txtStatusDl;
	private Handler handler = new Handler();
	Button read, delete;
	String ID;
	String title;
	String linkImage;
	private MyThread runnable;
	Resources res;
	View view;
	private boolean upload_status = false;
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(GlobalVariable.MEDIUM_SCREEN_SIZE.equals(GlobalVariable.finalScreenSize)){
		 setContentView(R.layout.book_information);
		}else{
			setContentView(R.layout.book_information_large);
		}
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		Intent i = getIntent();
		title = i.getStringExtra("TITLE").toString();
		final String FSize = i.getStringExtra("FILESIZE");
		String desc = i.getStringExtra("DESC").toString();
		String time = i.getStringExtra("TIME").toString();
		//String fileSize = i.getStringExtra("FILESIZE").toString();
		linkImage = i.getStringExtra("FILEIMAGE").toString();
		objBean = (Item_Magazine) i.getSerializableExtra("item_magazine");
		//pdfUrl = i.getStringExtra("PDF_URL").toString();
		res = getResources();
		ImageView imv = (ImageView) findViewById(R.id.image);
		TextView titleButtom = (TextView) findViewById(R.id.titlebuttom);
		TextView desct = (TextView) findViewById(R.id.desc_input);
		TextView timet = (TextView) findViewById(R.id.publisherDate_input);
		TextView fSize = (TextView) findViewById(R.id.fileSize_input);
		txtStatusDl = (TextView) findViewById(R.id.dlStatusInfo);
		progress = (ProgressBar) findViewById(R.id.infoBar);
		progress.setVisibility(View.INVISIBLE);
		read = (Button) findViewById(R.id.readPDFInfo);
		delete = (Button) findViewById(R.id.deleteBtnInfo);
		read.setVisibility(View.INVISIBLE);
		delete.setVisibility(View.INVISIBLE);
		final Button btnDownloadInfo = (Button) findViewById(R.id.btnDownloadInfo);
		final Magazine mag = Entity.query(Magazine.class).where("id").eq(objBean.getId()).execute();
		if(mag!=null){
			btnDownloadInfo.setBackgroundResource(R.drawable.download_button_selected);
			btnDownloadInfo.setEnabled(false);
			read.setVisibility(View.VISIBLE);
			delete.setVisibility(View.VISIBLE);
			btnDownloadInfo.setVisibility(View.INVISIBLE);
			delete.setBackgroundResource(R.drawable.download_button_selected);
		}
		
		
		
		btnDownloadInfo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				startDownload();
				btnDownloadInfo.setEnabled(false);
				btnDownloadInfo.setTextColor(Color.GRAY);
				progress.setVisibility(View.VISIBLE);
			}
		});

		read.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Magazine magforead = Entity.query(Magazine.class).where("id").eq(objBean.getId()).execute();
				if(magforead==null){
					Toast.makeText(getApplicationContext(), "Cannot read this file.. Please come back again", Toast.LENGTH_SHORT).show();
				}else{
					File file = new File(mag.path);
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(file), "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
					startActivity(intent);
				}
			}
		});

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.profile)
				.showImageForEmptyUrl(R.drawable.profile).cacheInMemory()
				.cacheOnDisc().build();
		imageLoader = ImageLoader.getInstance();

		imageLoader.init(ImageLoaderConfiguration
				.createDefault(BookInformation.this));
		imageLoader.displayImage(linkImage, imv, options,
				new ImageLoadingListener() {
					@Override
					public void onLoadingComplete() {

					}

					@Override
					public void onLoadingFailed() {
					}

					@Override
					public void onLoadingStarted() {

					}
				});

//		titletop.setText(title);
		titleButtom.setText(title);
		desct.setText(desc);
		timet.setText(time);
		fSize.setText(FSize);
		goback = (ImageView) findViewById(R.id.goback);
		goback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(BookInformation.this,MainActivity.class);
				startActivity(i);
				finish();
			}
		});
	}



	public void startDownload() {

		runnable = new MyThread();
		new Thread(runnable).start();

	}
	private class MyThread implements Runnable {

		private Boolean stop = false;
		private int Status = 0;
		private int count = 0;
		private int count2 = 0;

		public MyThread() {
		}

		public Boolean getStop() {
			return stop;
		}

		public void setStop(Boolean stop) {
			this.stop = stop;
		}

		public void init() {
			this.count = 0;
			this.count2 = 0;
		}

		@Override
		public void run() {

			while (!getStop()) {
				int count = 0;
				int count2 = 0;
				try {
					File Directory = new File(
							Environment.getExternalStorageDirectory()
									+ "/Magazine/download/Mag_"
									+ objBean.getId());
					if (!Directory.exists()) {
						Directory.mkdirs();
					}
					URL url2 = new URL(objBean.getLink());
					URLConnection conexion2 = url2.openConnection();
					conexion2.connect();
					InputStream input2 = new BufferedInputStream(
							url2.openStream());
					final String tumbName = objBean.getLink().substring(
							objBean.getLink().lastIndexOf('/') + 1,
							objBean.getLink().length());

					File imageThumb = new File(Directory, tumbName);
					OutputStream output2 = new FileOutputStream(imageThumb);
					byte data2[] = new byte[1024];
					while ((count2 = input2.read(data2)) != -1) {
						output2.write(data2, 0, count2);
					}

					output2.flush();
					output2.close();
					input2.close();

					URL url = null;
					URLConnection conexion = null;
					int lenghtOfFile = 0;

					InputStream input = null;

					String fileName[] = new String[objBean.getImg_paths().size()];

					File outputFile = null;
					OutputStream output = null;

					for (int i = 0; i < objBean.getImg_paths().size(); i++) {
						String link = objBean.getImg_paths().get(i);
						url = new URL(link);
						conexion = url.openConnection();
						conexion.connect();
						lenghtOfFile += conexion.getContentLength();

					}

					long total = 0;
					for (int i = 0; i < objBean.getImg_paths().size(); i++) {
						String link = objBean.getImg_paths().get(i);
						url = new URL(link);
						input = new BufferedInputStream(url.openStream());
						fileName[i] = link.substring(link.lastIndexOf('/') + 1,
								link.length()).replaceAll(".jpg", ".dpe");
						outputFile = new File(Directory, fileName[i]);
						output = new FileOutputStream(outputFile);
						byte data[] = new byte[1024];

						while ((count = input.read(data)) != -1) {
							// output.write(data, 0, count);
							if (!getStop()) {
								total += count;
								Status = (int) ((total * 100) / lenghtOfFile);
								output.write(data, 0, count);
								// // Update ProgressBar
								handler.post(new Runnable() {
									public void run() {
										if (!getStop()) {
											updateStatus(Status);
										}
									}
								});
							} else {
								File pdfFile = new File(
										Environment
												.getExternalStorageDirectory()
												+ "/Magazine/download/Mag_"
												+ objBean.getId());
								DeleteRecursive(pdfFile);
							}
						}
					}

					output.flush();
					output.close();
					input.close();

					List<Magazine> listMag = Entity.query(Magazine.class)
							.executeMulti();

					for (Magazine mg : listMag) {
						mg.status = "N";
						mg.save();
					}

					if (!getStop()) {
						Magazine mag = new Magazine();
						mag.id = new Integer(objBean.getId());
						mag.title = objBean.getTitle();
						mag.tumbnail = Environment
								.getExternalStorageDirectory()
								+ "/Magazine/download/Mag_"
								+ objBean.getId()
								+ "/" + tumbName;
						mag.status = "Y";
						mag.iss = String.valueOf(mag.getPk());
						mag.save();
						for (String s : fileName) {
							mag.id = new Integer(objBean.getId());
							Images img = new Images();
							img.id = img.getPk();
							img.magazine = mag;
							img.path = Environment
									.getExternalStorageDirectory()
									+ "/Magazine/download/Mag_"
									+ objBean.getId() + "/" + s;
							img.save();
						}

						setStop(true);
					}

				} catch (Exception e) {
					e.printStackTrace();
					setStop(true);

				}
			}

		}
	}
	private void updateStatus(int status) {
		
		ProgressBar progress = (ProgressBar) findViewById(R.id.infoBar);
		progress.setVisibility(View.VISIBLE);
		progress.setProgress(status);

		TextView txtStatus = (TextView) findViewById(R.id.dlStatusInfo);
		txtStatus.setTextColor(Color.parseColor(GlobalVariable.BLUE_COLOR));
		txtStatus.setText(res.getString(R.string.download_status_inprogress)
				+ String.valueOf(status) + "%");

		Button btnRead = (Button) findViewById(R.id.readPDFInfo);
		Button btnDel = (Button) findViewById(R.id.deleteBtnInfo);
		Button btnDownloadInfo = (Button) findViewById(R.id.btnDownloadInfo);
		if (status >= 100) {
			txtStatus.setText(res.getString(R.string.download_status_complete));
			progress.setVisibility(View.GONE);
			upload_status = true;
			btnRead.setVisibility(View.VISIBLE);
			btnDel.setVisibility(View.VISIBLE);
			btnDownloadInfo.setVisibility(View.GONE);

		}

	}
	public void DeleteRecursive(File fileOrDirectory) {
		if (fileOrDirectory.isDirectory())
			for (File child : fileOrDirectory.listFiles())
				DeleteRecursive(child);

		fileOrDirectory.delete();
	}
}
